import axios from 'axios'
import querystring from 'querystring'
import router from '../router'
import store from '../store'
import { AlertModule } from 'vux'

var defaultOpt = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Terminal-Type': 'innerH5'
  }
}

export default class Ajax {
  static async request (opt) {
    opt = Object.assign({}, defaultOpt, opt)
    let res
    try {
      res = await axios.request(opt)
      if (res.data.code == 1003) {
        AlertModule.show({
          title: '提示',
          content: '登陆已失效，请重新登陆。',
          onShow () {
          },
          onHide () {
            router.replace({ name: 'login' })
            store.commit('logout')
          }
        })
        return
      }
    } catch (e) {
      res = {
        data: {},
        msg: '网络错误,请稍后再试'
      }
    }
    return res.data
  }

  static async get (url, params = {}) {
    let opt = {
      method: 'get',
      url,
      params
    }
    return await Ajax.request(opt)
  }

  static async post (url, data = {}, params = {}) {
    if (typeof data === 'string') {

    } else {
      data = querystring.stringify(data)
    }

    let opt = {
      method: 'post',
      url,
      data: data,
      params: params
    }
    return await Ajax.request(opt)
  }

  static async formPost (url, fromData) {
    let opt = {
      method: 'post',
      url,
      data: fromData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
    return await Ajax.request(opt)
  }
}
